/*
 * @lc app=leetcode.cn id=19 lang=cpp
 *
 * [19] 删除链表的倒数第 N 个结点
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

class Solution
{
public:
    ListNode *removeNthFromEnd(ListNode *head, int n)
    {
        //删除倒数第n个节点 双指针
        ListNode *dummyHead = new ListNode(0);
        dummyHead->next = head;
        ListNode *pre = dummyHead;
        ListNode *cur = dummyHead;
        while (cur->next && n) //
        {
            cur = cur->next;
        }
        while (cur->next)
        {
            cur = cur->next;
            pre = pre->next;
        }
        ListNode *tmp = pre->next;
        pre->next = pre->next->next;
        delete tmp;
        return dummyHead->next;
    }
};
// @lc code=end
